import time,re,traceback
#自己的宏定义
from libs.mypthon import DEFINE


#生成字幕文件
#优化字幕长度,返回列表ass_list,列表的每一个元素为字典,包含开始,结束时间,字幕内容
def textToass_list(filename,tarlen=0,len_range=0):
    '''
    如果tarlen=0,则不进行优化字幕长度
    :param filename: str
    :param tarlen: int
    :param len_range: int
    :return: list
    '''
    new_list=[]
    clear_data_dict={DEFINE.KEY_TEXT: '', DEFINE.KEY_BENGINTIME:0, DEFINE.KEY_ENDTIME:0}
    data_dict=clear_data_dict
    #获取文本数据
    with open(filename,'r',encoding='utf-8') as ori_file:
        ori_list=eval(ori_file.read())

    # 优化字幕长度(短变长)
    if tarlen!=0:
        i = 0
        for item in ori_list:
            bo_clear=False
            # data_dict赋值为空,需要赋值为本次数据
            if data_dict==clear_data_dict:
                data_dict=item
                text=item[DEFINE.KEY_TEXT]
            else:
                text= data_dict[DEFINE.KEY_TEXT] + item[DEFINE.KEY_TEXT]
            text_len=(len(text))
            #长度超出范围,并且data_dict为本次数据
            if text_len>tarlen+len_range and i==0:
                data_dict=item
                zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
                #长变短只可以中英
                if (re.match(r'[a-z]+',text,re.I)!=None)or(zhPattern.search(text)!=None):
                    #将本次数据,按照 句 分短,用语速+字符数 计算大概时间,分好后添加到 new_list
                    zi_list=re.split('[.。]',text)
                    # del zi_list[-1]
                    # 本句的平均语速，单位：字数/分钟。
                    SpeechRate=int(data_dict[DEFINE.KEY_SpeechRate])
                    rate=(60*1000)/SpeechRate
                    i=0
                    last_endtime=0
                    for zi in zi_list:
                        if len(zi)==0:
                            continue
                        zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
                        bo_isok=False
                        #英文单词数
                        if re.match(r'[a-z]+',zi,re.I)!=None:
                            wordnum=len(zi.split(' '))
                            bo_isok=True
                        #中文
                        elif zhPattern.search(zi)!=None:
                            wordnum=len(zi)
                            bo_isok=True
                        if bo_isok==True:
                            time=rate*wordnum
                            if i==0:
                                begintime = int(data_dict[DEFINE.KEY_BENGINTIME])
                            else:
                                begintime=last_endtime
                            endtime=begintime+time
                            last_endtime=endtime
                            i=i+1
                            new_list.append({DEFINE.KEY_TEXT: zi + '.', DEFINE.KEY_BENGINTIME:begintime,
                                             DEFINE.KEY_ENDTIME:endtime})
                else:
                    new_list.append(data_dict)
                data_dict=clear_data_dict
                bo_clear=True
            # 长度超出范围,并且data_dict为上一次数据(上一次的数据不会超出范围)
            elif text_len > tarlen + len_range:
                new_list.append(data_dict)
                data_dict=item#本次数据还未利用,下次需要
            #长度不够
            elif text_len<tarlen:
                # 本次数据还未利用
                data_dict[DEFINE.KEY_TEXT]=text
                data_dict[DEFINE.KEY_ENDTIME]=item[DEFINE.KEY_ENDTIME]
            #长度正好,本次数据已用,data_dict赋值为空
            elif text_len>=tarlen and text_len <=tarlen+len_range:
                data_dict[DEFINE.KEY_TEXT] = text
                data_dict[DEFINE.KEY_ENDTIME] = item[DEFINE.KEY_ENDTIME]
                new_list.append(data_dict)
                data_dict=clear_data_dict
                bo_clear=True
            i = i + 1
            if bo_clear==True:
                i=0
    else:
        new_list=ori_list
    return new_list

# 由ass_list制作ass字幕
def textToass_file(ass_list,savefilename,arg_dict,MarginL=15,MarginR=15,MarginV=15):
    '''
    由ass_list制作ass字幕
    :param ass_list: list
    :param savefilename: str
    :param arg_dict: dict
    :return: Node
    '''
    if type(ass_list)!=type(list()):
        msg='def textToass_file(ass_list,savefilename,arg_dict,MarginL=15,MarginR=15,MarginV=15)中ass_list非list '
        return False,msg
    try:
        #制作ass字幕
        head='''[Script Info]
;
Title: 
Original Script: 
Original Translation: 'jingting|up:MaofU'
Original Timing:  'jingting|up:MaofU'
Original Editing:  'jingting|up:MaofU'
Script Updated By:  'jingting|up:MaofU'
Update Details: 
ScriptType: v4.00+
Collisions: Normal
PlayResX: 384
PlayResY: 288
Timer: 100.0000
Synch Point: 
WrapStyle: 0
ScaledBorderAndShadow: Yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, Bold, Italic, Underline, Spacing, Alignment , Encoding ,MarginL,MarginR,MarginV
Style: Default,{},{},{},{},{},{},{},{},134,{},{},{}
'''.format(arg_dict[DEFINE.KEY_assStyle_Fontname], arg_dict[DEFINE.KEY_assStyle_Fontsize], arg_dict[
            DEFINE.KEY_assStyle_PrimaryColour], arg_dict[DEFINE.KEY_assStyle_Bold], arg_dict[
                            DEFINE.KEY_assStyle_Italic],
           arg_dict[DEFINE.KEY_assStyle_Underline], arg_dict[DEFINE.KEY_assStyle_Spacing], arg_dict[
                            DEFINE.KEY_assStyle_Alignment], MarginL, MarginR, MarginV)

        body_list=[]
        body_list.append('''[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n''')
        for item in ass_list:
            #时间转换 毫秒转字符00:00:00.00
            if type(item[DEFINE.KEY_BENGINTIME])==type(int()):
                begint=msecToTime(item[DEFINE.KEY_BENGINTIME])
            else:
                begint = item[DEFINE.KEY_BENGINTIME]
            if type(item[DEFINE.KEY_ENDTIME])==type(int()):
                endt=msecToTime(item[DEFINE.KEY_ENDTIME])
            else:
                endt=item[DEFINE.KEY_ENDTIME]
            text=str(item[DEFINE.KEY_TEXT])
            text=text.replace('\n','\\N')
            string='Dialogue: 0,{},{},*Default,,0000,0000,0000,,{}'.format(begint,endt,text)
            body_list.append(string+'\n')

        file_data=head+''.join(body_list)
        #写入文件
        with open(savefilename,mode='w+',encoding='utf-8') as file:
            file.write(file_data)
    except Exception:
        msg=traceback.format_exc()
        print(msg)
        return False,msg
    else:
        return True,''

#时间转换 毫秒to 00:00:42.60
def msecToTime(msec):
    """

    :rtype: object
    """
    try:
        msec=int(msec)
    except Exception as e:
        print(msec,e)
        return
    timeStamp = float(msec/1000)
    timeArray = time.localtime(timeStamp)
    h=int((time.strftime("%H", timeArray)))
    h=h-8
    if h>=0 and h<=9:
        h_str='0{}'.format(h)
    else:
        h_str=str(h)
    m=(time.strftime("%M", timeArray))
    s=(time.strftime("%S", timeArray))
    ms=msec%1000
    ms_str='{:.2}'.format(str(ms))
    tm = '{}:{}:{}.{}'.format(h_str, m, s, ms_str)
    return tm

#由ass_list获取录音文件时长
def get_asslist_lastTime(ass_list):
    '''
    由ass_list获取录音文件时长
    :param ass_list: list
    :return: float(单位:秒
    '''
    time=0
    for item in ass_list:
        time=item[DEFINE.KEY_ENDTIME]
    time=time/(1000)
    return time

if __name__ == '__main__':
    print('')
    print(msecToTime(34687.5))